package org.filehanding.controller;

import org.apache.commons.lang3.StringUtils;
import org.filehanding.vo.ResponseValue;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;

/**
 * Created by liguo on 2016/5/14.
 */
public class BaseController {
    protected ResponseValue constructSuccessResponse(Object result) {
        ResponseValue responseValue = new ResponseValue();
        responseValue.setCode(ResponseValue.RESPONSE_CODE_SUCCESS);
        responseValue.setResult(result);
        return responseValue;
    }
    protected ResponseValue constructSuccessDefaultResponse() {
        ResponseValue responseValue = new ResponseValue();
        responseValue.setCode(ResponseValue.RESPONSE_CODE_SUCCESS);
        return responseValue;
    }
    protected ResponseValue constructNotAcceptResponse(String message) {
        ResponseValue responseValue = new ResponseValue();
        responseValue.setCode(ResponseValue.RESPONSE_CODE_NOT_ACCEPT);
        responseValue.setMessage(message);
        return responseValue;
    }

    protected ResponseValue constructCheckResponse(BindingResult result) {
        if (result.hasErrors()) {
            ResponseValue responseValue = new ResponseValue();
            responseValue.setCode(ResponseValue.RESPONSE_CODE_NOT_ACCEPT);
            int errorCount = result.getErrorCount();
            List<ObjectError> errors = result.getAllErrors();
            if (errors != null && errorCount > 0) {
                ObjectError oe = errors.get(0);
                if (StringUtils.isEmpty(oe.getDefaultMessage())) {
                    responseValue.setMessage(oe.getCode());
                } else {
                    responseValue.setMessage(oe.getDefaultMessage());
                }
            } else {
                responseValue.setMessage("输入信息有误，请重新输入");
            }
            responseValue.setResult(result.getAllErrors());
            return responseValue;
        }
        return null;
    }
}
